/*
 * Tencent is pleased to support the open source community by making ovCompose available.
 * Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.tencent.compose.sample.test

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.material.Button
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Scaffold
import androidx.compose.material.Text
import androidx.compose.material.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow

/**
 * 测试工具类
 */
object TestUtils {
    
    /**
     * 验证邮箱格式
     */
    fun isValidEmail(email: String): Boolean {
        val emailRegex = "^[A-Za-z0-9+_.-]+@([A-Za-z0-9.-]+\\.[A-Za-z]{2,})$".toRegex()
        return emailRegex.matches(email)
    }
    
    /**
     * 验证手机号格式
     */
    fun isValidPhoneNumber(phoneNumber: String): Boolean {
        val phoneRegex = "^1[3-9]\\d{9}$".toRegex()
        return phoneRegex.matches(phoneNumber)
    }
    
    /**
     * 格式化价格
     */
    fun formatPrice(price: Double, currency: String = "CNY"): String {
        return when (currency) {
            "CNY" -> "¥${String.format("%.2f", price)}"
            "USD" -> "$${String.format("%.2f", price)}"
            "EUR" -> "€${String.format("%.2f", price)}"
            else -> "${currency}${String.format("%.2f", price)}"
        }
    }
    
    /**
     * 格式化文件大小
     */
    fun formatFileSize(bytes: Long): String {
        val units = arrayOf("B", "KB", "MB", "GB", "TB")
        var size = bytes.toDouble()
        var unitIndex = 0
        
        while (size >= 1024 && unitIndex < units.size - 1) {
            size /= 1024
            unitIndex++
        }
        
        return String.format("%.1f %s", size, units[unitIndex])
    }
    
    /**
     * 计算时间差
     */
    fun getTimeDifference(timestamp: Long): String {
        val now = System.currentTimeMillis()
        val diff = now - timestamp
        
        return when {
            diff < 60 * 1000 -> "刚刚"
            diff < 60 * 60 * 1000 -> "${diff / (60 * 1000)}分钟前"
            diff < 24 * 60 * 60 * 1000 -> "${diff / (60 * 60 * 1000)}小时前"
            diff < 7 * 24 * 60 * 60 * 1000 -> "${diff / (24 * 60 * 60 * 1000)}天前"
            else -> {
                val date = java.util.Date(timestamp)
                val formatter = java.text.SimpleDateFormat("MM-dd", java.util.Locale.getDefault())
                formatter.format(date)
            }
        }
    }
    
    /**
     * 生成随机字符串
     */
    fun generateRandomString(length: Int): String {
        val chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
        return (1..length)
            .map { chars.random() }
            .joinToString("")
    }
    
    /**
     * 生成随机ID
     */
    fun generateRandomId(): String {
        return System.currentTimeMillis().toString() + generateRandomString(6)
    }
    
    /**
     * 计算字符串相似度
     */
    fun calculateSimilarity(str1: String, str2: String): Double {
        val longer = if (str1.length > str2.length) str1 else str2
        val shorter = if (str1.length > str2.length) str2 else str1
        
        if (longer.isEmpty()) return 1.0
        
        val editDistance = levenshteinDistance(longer, shorter)
        return (longer.length - editDistance).toDouble() / longer.length
    }
    
    /**
     * 计算编辑距离
     */
    private fun levenshteinDistance(str1: String, str2: String): Int {
        val matrix = Array(str1.length + 1) { IntArray(str2.length + 1) }
        
        for (i in 0..str1.length) {
            matrix[i][0] = i
        }
        
        for (j in 0..str2.length) {
            matrix[0][j] = j
        }
        
        for (i in 1..str1.length) {
            for (j in 1..str2.length) {
                val cost = if (str1[i - 1] == str2[j - 1]) 0 else 1
                matrix[i][j] = minOf(
                    matrix[i - 1][j] + 1,      // deletion
                    matrix[i][j - 1] + 1,      // insertion
                    matrix[i - 1][j - 1] + cost // substitution
                )
            }
        }
        
        return matrix[str1.length][str2.length]
    }
    
    /**
     * 验证身份证号
     */
    fun isValidIdCard(idCard: String): Boolean {
        val idCardRegex = "^[1-9]\\d{5}(18|19|20)\\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx]$".toRegex()
        return idCardRegex.matches(idCard)
    }
    
    /**
     * 验证银行卡号
     */
    fun isValidBankCard(cardNumber: String): Boolean {
        val cleanCardNumber = cardNumber.replace("\\s".toRegex(), "")
        if (cleanCardNumber.length < 13 || cleanCardNumber.length > 19) return false
        
        var sum = 0
        var alternate = false
        
        for (i in cleanCardNumber.length - 1 downTo 0) {
            var n = cleanCardNumber[i].toString().toInt()
            
            if (alternate) {
                n *= 2
                if (n > 9) {
                    n = n / 10 + n % 10
                }
            }
            
            sum += n
            alternate = !alternate
        }
        
        return sum % 10 == 0
    }
    
    /**
     * 格式化银行卡号
     */
    fun formatBankCard(cardNumber: String): String {
        val cleanCardNumber = cardNumber.replace("\\s".toRegex(), "")
        return cleanCardNumber.chunked(4).joinToString(" ")
    }
    
    /**
     * 计算年龄
     */
    fun calculateAge(birthTimestamp: Long): Int {
        val birthDate = java.util.Date(birthTimestamp)
        val currentDate = java.util.Date()
        
        val birthCalendar = java.util.Calendar.getInstance()
        birthCalendar.time = birthDate
        
        val currentCalendar = java.util.Calendar.getInstance()
        currentCalendar.time = currentDate
        
        var age = currentCalendar.get(java.util.Calendar.YEAR) - birthCalendar.get(java.util.Calendar.YEAR)
        
        if (currentCalendar.get(java.util.Calendar.DAY_OF_YEAR) < birthCalendar.get(java.util.Calendar.DAY_OF_YEAR)) {
            age--
        }
        
        return age
    }
    
    /**
     * 获取星座
     */
    fun getZodiacSign(birthTimestamp: Long): String {
        val calendar = java.util.Calendar.getInstance()
        calendar.time = java.util.Date(birthTimestamp)
        
        val month = calendar.get(java.util.Calendar.MONTH) + 1
        val day = calendar.get(java.util.Calendar.DAY_OF_MONTH)
        
        return when {
            (month == 3 && day >= 21) || (month == 4 && day <= 19) -> "白羊座"
            (month == 4 && day >= 20) || (month == 5 && day <= 20) -> "金牛座"
            (month == 5 && day >= 21) || (month == 6 && day <= 21) -> "双子座"
            (month == 6 && day >= 22) || (month == 7 && day <= 22) -> "巨蟹座"
            (month == 7 && day >= 23) || (month == 8 && day <= 22) -> "狮子座"
            (month == 8 && day >= 23) || (month == 9 && day <= 22) -> "处女座"
            (month == 9 && day >= 23) || (month == 10 && day <= 23) -> "天秤座"
            (month == 10 && day >= 24) || (month == 11 && day <= 22) -> "天蝎座"
            (month == 11 && day >= 23) || (month == 12 && day <= 21) -> "射手座"
            (month == 12 && day >= 22) || (month == 1 && day <= 19) -> "摩羯座"
            (month == 1 && day >= 20) || (month == 2 && day <= 18) -> "水瓶座"
            (month == 2 && day >= 19) || (month == 3 && day <= 20) -> "双鱼座"
            else -> "未知"
        }
    }
    
    /**
     * 生成二维码内容
     */
    fun generateQRCodeContent(type: String, data: Map<String, String>): String {
        return when (type) {
            "url" -> data["url"] ?: ""
            "text" -> data["text"] ?: ""
            "contact" -> "BEGIN:VCARD\n" +
                    "FN:${data["name"]}\n" +
                    "TEL:${data["phone"]}\n" +
                    "EMAIL:${data["email"]}\n" +
                    "END:VCARD"
            "wifi" -> "WIFI:T:${data["security"]};S:${data["ssid"]};P:${data["password"]};H:${data["hidden"]};"
            else -> data.toString()
        }
    }
    
    /**
     * 解析URL参数
     */
    fun parseUrlParameters(url: String): Map<String, String> {
        val parameters = mutableMapOf<String, String>()
        
        try {
            val uri = java.net.URI(url)
            val query = uri.query
            
            if (query != null) {
                query.split("&").forEach { param ->
                    val parts = param.split("=", limit = 2)
                    if (parts.size == 2) {
                        parameters[parts[0]] = java.net.URLDecoder.decode(parts[1], "UTF-8")
                    }
                }
            }
        } catch (e: Exception) {
            // 解析失败，返回空Map
        }
        
        return parameters
    }
    
    /**
     * 构建URL
     */
    fun buildUrl(baseUrl: String, parameters: Map<String, String>): String {
        val uriBuilder = java.net.URIBuilder(baseUrl)
        
        parameters.forEach { (key, value) ->
            uriBuilder.addParameter(key, value)
        }
        
        return uriBuilder.build().toString()
    }
    
    /**
     * 计算两点间距离
     */
    fun calculateDistance(lat1: Double, lon1: Double, lat2: Double, lon2: Double): Double {
        val earthRadius = 6371.0 // 地球半径（公里）
        
        val dLat = Math.toRadians(lat2 - lat1)
        val dLon = Math.toRadians(lon2 - lon1)
        
        val a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
                Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
                Math.sin(dLon / 2) * Math.sin(dLon / 2)
        
        val c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a))
        
        return earthRadius * c
    }
    
    /**
     * 生成颜色代码
     */
    fun generateColorCode(): String {
        val colors = listOf(
            "#FF5722", "#E91E63", "#9C27B0", "#673AB7", "#3F51B5",
            "#2196F3", "#03A9F4", "#00BCD4", "#009688", "#4CAF50",
            "#8BC34A", "#CDDC39", "#FFEB3B", "#FFC107", "#FF9800"
        )
        return colors.random()
    }
    
    /**
     * 验证颜色代码
     */
    fun isValidColorCode(colorCode: String): Boolean {
        val colorRegex = "^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$".toRegex()
        return colorRegex.matches(colorCode)
    }
    
    /**
     * 生成测试数据流
     */
    fun generateTestDataFlow(): Flow<String> = flow {
        val testData = listOf(
            "用户登录成功",
            "订单创建完成",
            "支付处理中",
            "商品已发货",
            "评价已提交",
            "退款已处理",
            "优惠券已使用",
            "积分已到账"
        )
        
        while (true) {
            emit(testData.random())
            delay(2000)
        }
    }
    
    /**
     * 模拟网络请求
     */
    suspend fun simulateNetworkRequest(delayMs: Long = 1000): String {
        delay(delayMs)
        return "请求完成"
    }
    
    /**
     * 模拟文件上传
     */
    suspend fun simulateFileUpload(fileSize: Long, progressCallback: (Int) -> Unit): Boolean {
        val totalSteps = 100
        val stepSize = fileSize / totalSteps
        
        repeat(totalSteps) { step ->
            delay(50) // 模拟上传延迟
            progressCallback(((step + 1) * 100 / totalSteps).toInt())
        }
        
        return true
    }
    
    /**
     * 模拟数据下载
     */
    suspend fun simulateDataDownload(dataSize: Long, progressCallback: (Int) -> Unit): ByteArray {
        val totalSteps = 100
        val stepSize = dataSize / totalSteps
        
        repeat(totalSteps) { step ->
            delay(30) // 模拟下载延迟
            progressCallback(((step + 1) * 100 / totalSteps).toInt())
        }
        
        return ByteArray(dataSize.toInt())
    }
}

/**
 * 测试工具页面
 */
@Composable
fun TestUtilsPage() {
    var testResult by remember { mutableStateOf("") }
    
    Column(
        modifier = Modifier.padding(16.dp),
        verticalArrangement = Arrangement.spacedBy(16.dp)
    ) {
        Text("测试工具", fontSize = 18.sp, fontWeight = FontWeight.Bold)
        
        Button(
            onClick = {
                val email = "test@example.com"
                testResult = "邮箱验证: $email -> ${TestUtils.isValidEmail(email)}"
            }
        ) {
            Text("测试邮箱验证")
        }
        
        Button(
            onClick = {
                val price = 123.45
                testResult = "价格格式化: $price -> ${TestUtils.formatPrice(price)}"
            }
        ) {
            Text("测试价格格式化")
        }
        
        if (testResult.isNotEmpty()) {
            Text("测试结果: $testResult")
        }
    }
}
